package com.boby.homecamera.adapter

import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.boby.homecamera.R
import com.boby.homecamera.adapter.VideoAdapter.VideoViewHolder
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.db.VideoTable
import com.boby.homecamera.net.Api
import com.boby.lib_common.BaseApplication
import com.boby.lib_common.extens.dp
import com.boby.lib_common.extens.setCornerRadius
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.bumptech.glide.signature.ObjectKey
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class VideoAdapter(): RecyclerView.Adapter<VideoViewHolder>() {
    var data: MutableList<VideoTable.Video> = mutableListOf()
    private var itemClickListener: ((index:Int,item:VideoTable.Video)->Unit ?)? = null
    private var ip:String = ""
    private var token:String = ""
    private var httpPort = Constant.HTTP_SERVER_PORT
    var firstMarginTop = 0
    var lastMarginBottom = 0
    fun setIp(ip:String,token:String,httpPort:Int,){
        this.ip = ip
        this.token = token
        this.httpPort = httpPort
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
      val view =  LayoutInflater.from(parent.context).inflate(R.layout.item_video,parent,false)
        return VideoViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        val item = data[position]
//        if(position == 0){
//            holder.itemView.setPadding(0,firstMarginTop,0,0)
//        }else if (position == data.size-1){
//            holder.itemView.setPadding(0,0,0,lastMarginBottom)
//        }else{
//            holder.itemView.setPadding(0,0,0,0)
//        }
        holder.time_length.text= formatTimemmss((item.endTime!! - item.startTime!!)/1000 )
        holder.time.text= formatTimeHHmmss(item.startTime!!)
        holder.itemView.setOnClickListener {
            itemClickListener?.invoke(position,item)
        }


        val currentUrl = GlideUrl(
            "${Api.getRealUrl(ip,httpPort)}/video/getpic/?path=${item.path}",
            LazyHeaders.Builder()
                .addHeader("Authorization", "Bearer ${token}")
                .build()
        )
        holder.iv_video_preview.tag = currentUrl
        holder.iv_video_preview.setCornerRadius(10f.dp())
        Glide.with(holder.iv_video_preview.context)
            .load(currentUrl)
            .dontAnimate()
            .into(object : CustomTarget<Drawable>() {
                override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                    // ✅ 加载完成后再判断是否仍是当前绑定的 item
                    if (holder.iv_video_preview.tag == currentUrl) {
                        holder.iv_video_preview.setImageDrawable(resource)
                    }
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    holder.iv_video_preview.setImageDrawable(placeholder)
                }
            })
//            .into(holder.iv_video_preview)
    }
    override fun onViewRecycled(holder: VideoViewHolder) {
        super.onViewRecycled(holder)
        Glide.with(holder.iv_video_preview.context)
            .clear(holder.iv_video_preview)
    }

    override fun getItemCount(): Int {
      return  data.size
    }


    fun setItemClickListener(listener: (index:Int,item:VideoTable.Video) -> Unit ){
        this.itemClickListener = listener
    }

   public class VideoViewHolder(var itemView:View): ViewHolder(itemView){
        val time_length = itemView.findViewById<TextView>(R.id.time_length)
        val time = itemView.findViewById<TextView>(R.id.time)
        val iv_video_preview = itemView.findViewById<ImageView>(R.id.iv_video_preview)
    }
//
//    fun formatTimeHHmmss(timeValue: Long): String {
//        val hour = timeValue / 3600
//        val minute = (timeValue % 3600) / 60
//        val second = timeValue % 60
//        return String.format("%02d:%02d:%02d", hour, minute, second)
//    }
    fun formatTimeHHmmss(timestampMillis: Long): String {
        val sdf: SimpleDateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        val date: Date = Date(timestampMillis)
        return sdf.format(date)
    }
    fun formatTimemmss(timeValue: Long): String {
//        val hour = timeValue / 3600
        val minute = (timeValue % 3600) / 60
        val second = timeValue % 60
        return String.format("%02d'%02d", minute, second)
    }
}